package TrappingRainWater_42;

public class Solution {
    public static void main(String[] args) {
        System.out.println(trap(new int[]{4, 2, 0, 3, 2, 5}));
    }

    public static int trap(int[] height) {
        if (height.length <= 2) {
            return 0;
        }
        int result = 0;
        int lp = 1;
        int rp = height.length - 2;
        int lMax = height[0];
        int rMax = height[height.length - 1];

        while (lp <= rp) {
            if (lMax >= rMax) {
                if (height[rp] < rMax) {
                    result += rMax - height[rp];
                }
                rMax = Math.max(height[rp], rMax);
                rp--;
            } else {
                if (height[lp] < lMax) {
                    result += lMax - height[lp];
                }
                lMax = Math.max(height[lp], lMax);
                lp++;
            }
        }
        return result;
    }


}





